﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using HtmlAgilityPack;
using System.IO;

/// <summary>
/// Summary description for GameScraper
/// </summary>
public class GameScraper
{

    const string scoresURL = "http://www.nfl.com/scores/2012/REG";


    public void UpdateWeek(int i)
    {
         string url = scoresURL + i.ToString();
         WebClient w = new WebClient();
         string s = w.DownloadString(url);
         HtmlDocument doc = new HtmlDocument();
         doc.LoadHtml(s);

         foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//div [@class='new-score-box-heading']"))
            {
                GetGame(link);
            }

         //doc.Save("file.htm");
    }

    private void GetGame(HtmlNode link)
    {
        var teams = (from lnks in link.Descendants()
                     where lnks.Name == "div" && lnks.Attributes["class"] != null && lnks.Attributes["class"].Value == "team-wrapper"
                     select lnks).ToList();
        //var teams = link.SelectNodes("//div [@class='team-wrapper']");

        int awayTeamID = GetTeamID(teams[0]);
        int homeTeamID = GetTeamID(teams[0]);



    }

    public int GetTeamID(HtmlNode teamNode)
    {
        HtmlNodeCollection col = new HtmlNodeCollection(teamNode);

        HtmlNode info = (from lnks in teamNode.Descendants()
                        where lnks.Name == "div" && lnks.Attributes["class"] != null && lnks.Attributes["class"].Value == "team-data"
                        select lnks).First();
         //HtmlNode info = col.SelectNodes(".//div [@class='team-data']")[0];
         HtmlNode name = info.SelectSingleNode(".//p [@class='team-name']");
         string teamName = name.InnerText;
         //int teamID = DataBase.Teams.GetTeamID(teamName);

         //if (teamID == -1)
         //{
         //    HtmlNode logoNode = teamNode.SelectSingleNode(".//img [@class='team-logo']");
         //    string icon = logoNode.Attributes["src"].Value;
         //    string website = name.FirstChild.Attributes["href"].Value;
         //    teamID = DataBase.Teams.InsertTeam(teamName, "www.nfl.com" + website, icon);
         //}

        
         return 1;
    }
}